package com.ktjiaoyu.crm.service.impl;

import com.ktjiaoyu.crm.entity.BasDict;
import com.ktjiaoyu.crm.entity.Product;
import com.ktjiaoyu.crm.entity.Storage;
import com.ktjiaoyu.crm.repository.BasDictRepository;
import com.ktjiaoyu.crm.service.IBasDictService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service(value = "basDictService")
public class BasDictServiceImpl implements IBasDictService {
    @Resource
    private BasDictRepository basDictRepository;
    @Override
    public Page<BasDict> findServiceType(Long dictId, String dictItem, Pageable pageable) {
        Specification<BasDict> storageSpecification = new Specification<BasDict>() {
            @Override
            public Predicate toPredicate(Root<BasDict> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (dictId!=null && dictId!=0){
                    predicates.add(criteriaBuilder.equal(root.get("dictId"),dictId));
                }
                if (dictItem!=null && !dictItem.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("dictItem"), "%"+dictItem+"%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return basDictRepository.findAll(storageSpecification, pageable);
    }

    @Override
    public void saveServiceType(BasDict basDict) {
        basDictRepository.save(basDict);
    }

    @Override
    public BasDict getDict(Long dictId) {
        return basDictRepository.findById(dictId).get();
    }

    @Override
    public void delServiceType(Long dictId) {
        basDictRepository.deleteById(dictId);
    }
}
